apiready = function(){

	var payinfo = {};
	var us = {
		money: 0,
		shopMoney: 0,
		score: 0,
		address: 0,
		isGoPay:0,
	};
	$(function(){
		if (!getUserinfo()) 
			return false;
		
		function a(){
			$('li.select_pay').bind('click', function(){
				$('li.select_pay input[type=radio]').removeAttr('checked');
				$('li.select_pay label').removeClass('selectedP');
				$(this).find('label').addClass('selectedP');
				$(this).find('input').attr('checked', 'checked');
			});
		}

		var b = function(){
			var userinfo = getUserinfo();
			var jsonData = localData.get('z_cart');
			PostData(config.url + '/app.php?act=zpayment&uid=' + userinfo.uid, {
				'cart': jsonData
			}, function(data){
				if (data['status'] == 1) {
					$('.comm-loading').hide();
					var html = '';
					for (var i in data['shoplist']) {
						html += '<li><a href="javascript:openItem(\'z_item\',' + data['shoplist'][i]['id'] + ',function(id){localData.set(\'z_goods_id\',id);});" class="gray6">' + data['shoplist'][i]['title'] + '  (' + data['shoplist'][i]['title2'] + ')</a>';
						html += '<span><em class="orange arial">' + data['shoplist'][i]['cart_gorenci'] + '</em>件';
						html += '</span></li>';
					}
					for (var i = 0; i < data['payapi'].length; i++) {
						payinfo[data['payapi'][i]['pay_id']] = {};
						payinfo[data['payapi'][i]['pay_id']]['pay_partner'] = data['payapi'][i]['pay_partner'];
						payinfo[data['payapi'][i]['pay_id']]['pay_key'] = data['payapi'][i]['pay_key'];
						payinfo[data['payapi'][i]['pay_id']]['pay_account'] = data['payapi'][i]['pay_account'];
						payinfo[data['payapi'][i]['pay_id']]['public_key'] = data['payapi'][i]['public_key'];
						payinfo[data['payapi'][i]['pay_id']]['private_key'] = data['payapi'][i]['private_key'];
					}
					$('section.g-pay-lst .comm-loading').before(html);
					
					$('#shopnum').val(data['count']);
					$('#hidBalance').val(data['money']);
					
					if (data['pay_type'] == 'error') {
						$('#btnPay').addClass('btnPay');
					}
					$('.add_address').click(function(){
						localData.set('reload', 'z_payment');
						randomSwitchBtn('add_address', api);
					});
					if (data['address'] == 'no') {
						us.address = 1;
					}
					else {
						$('.address').html(data['address']['sheng'] + data['address']['shi'] + data['address']['xian'] + data['address']['jiedao'] + '&nbsp;邮编：' + data['address']['youbian'] + '&nbsp;收货人：' + data['address']['shouhuoren'] + '&nbsp;手机号：' + data['address']['mobile']);
					}
					$('#hidShopMoney').val(data['MoenyCount']);
					$('.shoPMoenyCount').text(data['MoenyCount']);
					$('#hidPoints').val(data['hidPoints']);
					us.money = data['money'];
					us.score = data['hidPoints'];
					if (data['MoenyCount'] > data['money']) {
						us.shopMoney = data['MoenyCount'] - data['money'];
					}
					else {
						us.shopMoney = data['MoenyCount'];
					}
					$('.MoenyCount').text(us.shopMoney);
					$('.bag_money').text('您的余额不足（账户余额：' + data['money'] + '元）');
					$('.payplatform').after(data['paylist']);
               if(!data['paylist']){
			   	 us.isGoPay = 1;
				 $('.payplatform').hide();
				 $('#ulPayway').hide();
				 
			   }
					a();
					
					if (data['pay_type'] == 'ok') {
						$('.bag').show();
						$('.userrecharge').hide();
						$('.g-member').hide();
					}
					else 
						if (data['pay_type'] == 'error') {
							$('.bag').hide();
							$('.userrecharge').show();
							$('.g-member').show();
							//支付开始
							
							
							var cartinfo = localData.get('z_cart');
							if (!cartinfo) {
								return false;
							}
							if (!getUserinfo()) 
								return false;
							
							$('#form_paysubmit').submit(function(){
								var cartinfo = localData.get('z_cart');
								if (!cartinfo) {
									return false;
								}
								
								var userinfo = getUserinfo();
								var type = '';
								$('#ulBankList li input').each(function(e){
									if ($(this).attr('checked') == 'checked') {
										type = $(this).attr('item');
									}
								});
								if (!type || type == 'undefined') {
		if(us.isGoPay){
			if(api.systemType == 'ios'){
				api.openApp({
				    iosUrl: 'http://e.test.com/Cjson/alipay.html'
					//iosUrl:'http://mzttg.test.com/',
				});
			}else if(api.systemType == 'android'){
				api.openApp({
				    androidPkg: 'android.intent.action.VIEW',
				    mimeType: 'text/html',
				    uri: 'http://e.test.com/Cjson/alipay.html'
					//uri:'http://mzttg.test.com/',
				},function( ret, err ){
				    if( ret ){
				         //alert( JSON.stringify( ret ) );
				    }else{
				         //alert( JSON.stringify( err ) );
				    }
				});
			}
			return false;	
		}
									$.PageDialog.fail('请选择支付平台');
									return false;
								}
								if (us.address) {
									api.alert({
										title: '提示',
										msg: '请添加收货地址'
									}, function(index, err){
									});
									return false;
								}
								var sn = getOrder();
								if (type == 'wapalipay') {
									var obj = api.require('aliPay');
									api.showProgress({
										title: '正在提交',
										text: ''
									});
									$(this).ajaxSubmit({
										url: config.url + '/app.php?act=zgopayment&uid=' + userinfo.uid,
										dataType: 'json',
										beforeSend: function(){
											$('#btnPay').addClass('btnPay');
											$('.actionPay').addClass('private');
											$('.g-member').hide();
										},
										data: {
											submit: true,
											pay_type: type,
											code: sn,
											money: us.shopMoney,
											score: us.score,
											cart: cartinfo
										},
										success: function(data){
											if (data['status']) {
												obj.config({
													partner: config.alipay.app_id,
													seller: config.alipay.account,
													rsaPriKey: config.alipay.private_key,
													rsaPubKey: config.alipay.public_key,
													notifyURL: config.url + '/go_return_url.php'
												}, function(ret, err){
												
													if (!ret['status']) {
														GetJPData(config.url + '/app.php?act=removeorder&uid=' + userinfo.uid, {
															sncode: sn
														}, function(data){
														});
														return;
													}
													
													var subject = '购买商品';
													var body = '订单描述';
													var amount = 0.01;
													var tradeNO = sn;
													obj.pay({
														subject: subject,
														body: body,
														amount: amount,
														tradeNO: tradeNO
													}, function(ret, err){
														//if(ret['status']){
														if (ret.code == '9000') {
															api.hideProgress();
															api.showProgress({
																title: '订单处理中',
																text: ''
															});
															PostData(config.url + '/app.php?act=zpaysubmit&uid=' + userinfo.uid, {
																checkpay: 'money',
																bag: 'a',
																banktype: 'nobank',
																submit: true,
																cart: cartinfo
															}, function(json){
																if (json['status']) {
																	localData.remove('z_cart');
																	localData.remove('z_cart_num');
																	api.hideProgress();
																	api.alert({
																		title: '提示',
																		msg: json['msg']
																	}, function(index, err){
																		randomSwitchBtn('z_paysuccess', api);
																		appClose('z_payment', api);
																	});
																}
																else {
																	api.hideProgress();
																	api.alert({
																		title: '提示',
																		msg: json['msg']
																	}, function(index, err){
																		appClose('z_payment', api);
																	});
																}
															});
															return;
														}
														else {
															api.hideProgress();
															if (ret.code == '6001') {
																$('.actionPay').removeClass('private');
																$('.g-member').show();
																api.alert({
																	title: '提示',
																	msg: '取消支付'
																});
																return;
															}
															api.alert({
																title: '提示',
																msg: getStatus(ret.code)
															}, function(index, err){
																appClose('z_payment', api);
															});
														}
													/*  
													 }else{
													 api.hideProgress();
													 $('.actionPay').removeClass('private');
													 $('.g-member').show();
													 api.alert({title:'提示',msg:'取消支付'});
													 }
													 */
													});
												});
											}
											else {
												api.hideProgress();
												$('#btnPay').removeClass('btnPay');
												$('.actionPay').removeClass('private');
												$('#btnPay').hide();
												localData.remove('z_cart');
												localData.remove('z_cart_num');
												api.alert({
													title: '提示',
													msg: data['msg']
												}, function(index, err){
													appClose('z_payment', api);
												});
											}
										},
									});
								}
								else 
									if (type == 'wxpay_web') {
										var weiXin = api.require('weiXin');
										weiXin.registerApp(function(ret, err){
											if (ret.status) {
												api.showProgress({
													title: '正在提交',
													text: ''
												});
												$(this).ajaxSubmit({
													type: 'POST',
													url: config.url + '/app.php?act=zgopayment&uid=' + userinfo.uid,
													beforeSend: function(){
														$('#btnPay').addClass('btnPay');
														$('.actionPay').addClass('private');
														$('.g-member').hide();
													},
													data: {
														submit: 'true',
														pay_type: type,
														code: sn,
														money: us.shopMoney,
														score: us.score,
														cart: cartinfo
													},
													success: function(data){
														if (data['status'] == 1) {
															var wxPay = api.require('wxPay');
															wxPay.config({
																apiKey: config.wxpay.app_id,
																mchId: config.wxpay.mchid,
																partnerKey: config.wxpay.pay_key,
																notifyUrl: config.url + '/wxgo_return_url.php'
															}, function(ret, err){
																if (!ret.status) {
																	return;
																}
																wxPay.pay({
																	description: '购买商品',
																	totalFee: us.shopMoney*100,
																	tradeNo: sn,
																	spbillCreateIP: '196.168.1.1',
																	deviceInfo: 'APP',
																	detail: '购买商品',
																	attach: config.wxpay.pay_key,
																	feeType: 'CNY'
																}, function(ret, err){
																
																	api.hideProgress();
																	if (typeof err == 'object') {
																		$('.actionPay').removeClass('private');
																		$('.g-member').show();
																		api.alert({
																			title: '提示',
																			msg: '取消支付'
																		});
																		return false;
																	}
																	
																	if (ret['status']) {
																		api.showProgress({
																			title: '订单处理中',
																			text: ''
																		});
																		PostData(config.url + '/app.php?act=zpaysubmit&uid=' + userinfo.uid, {
																			checkpay: 'money',
																			bag: 'a',
																			banktype: 'nobank',
																			submit: 'true',
																			cart: cartinfo
																		}, function(json){
																			localData.remove('z_cart');
																			localData.remove('z_cart_num');
																			api.hideProgress();
																			if (json['status']) {
																				api.alert({
																					title: '提示',
																					msg: json['msg']
																				}, function(index, err){
																					randomSwitchBtn('z_paysuccess', api);
																					appClose('z_payment', api);
																					appClose('z_cart', api);
																				});
																			}
																			else {
																				api.alert({
																					title: '提示',
																					msg: json['msg']
																				}, function(index, err){
																					appClose('z_payment', api);
																				});
																			}
																		});
																	}
																	else {
																		//支付失败
																		localData.remove('z_cart');
																		localData.remove('z_cart_num');
																		api.hideProgress();
																		api.alert({
																			title: '提示',
																			msg: json['msg']
																		}, function(index, err){
																			appClose('payment', api);
																		});
																	}
																});
															});
														}
														else {
															//提交失败
															api.hideProgress();
															$('.actionPay').removeClass('private');
															$('.g-member').show();
															api.alert({
																title: '提示',
																msg: data['msg']
															}, function(index, err){
																appClose('z_payment', api);
															});
														}
													}
												});
											}
											else {
												//注册失败
												api.alert({
													msg: err.msg
												});
											}
										});
									}//微信支付 end
								return false;
							});
							
						//支付结束
						}
					exc();
				}
				else {
					$.PageDialog.fail(data['msg']);
					//appClose('payment');
				};
							});
			
			function exc(){
				var a = false;
				var x = parseInt($("#hidShopMoney").val());
				var ffdk = parseInt($("#pointsbl").val());
				var d = $("#hidBalance").val();
				var t = parseInt($("#hidPoints").val());
				var c = $("#spPoints");
				var p = $("#spBalance");
				var h = null;
				var shopnum = parseInt($("#shopnum").val());
				var r = "招商银行";
				//var g = parseInt(t / 100) > x ? x: parseInt(t / 100);
				var g = ffdk > x ? x : ffdk;
				var w = 0;
				var e = 0;
				var checkpay = 'nosel';//选择支付方式
				var banktype = 'nobank';
				
				if (g < x) {
					var j = parseInt(d);
					if (j > 0) {
						var i = x - g;
						if (j >= i) {
							w = i;
						}
						else {
							w = j;
							e = i - j;
						}
					}
					else {
						e = x - g;
					}
				}
				
				var q = function(y){
					g = y;
					if (y > 0) {
						c.parent().removeClass("z-pay-grayC");
						c.attr("sel", "1").attr("class", "z-pay-mentsel").next("span").html('福分支付<em class="orange">' + y + ".00</em>元（您的福分：" + t + "）");
						checkpay = 'fufen';
						banktype = 'nobank';
					}
					else {
						c.attr("sel", "0").attr("class", "z-pay-ment").next("span").html('福分支付<em class="orange">0.00</em>元（您的福分：' + t + "）");
					}
				};
				var f = function(y){
					w = y;
					if (y > 0) {
						p.parent().removeClass("z-pay-grayC");
						p.attr("sel", "1").attr("class", "z-pay-mentsel").next("span").html('余额支付<em class="orange">' + y + ".00</em>元（账户余额：" + d + " 元）");
						checkpay = 'money';
						banktype = 'nobank';
					}
					else {
						p.attr("sel", "0").attr("class", "z-pay-ment").next("span").html('余额支付<em class="orange">0.00</em>元（账户余额：' + d + " 元）");
					}
				};
				var k = function(y){
				};
				if (ffdk > 0) {
					c.parent().click(function(){
						if (c.attr("sel") == 1) {
							q(0);
							n(x);
						}
						else {
							var y = ffdk;
							if (y > 0) {
								q(y >= x ? x : y);
								n(y >= x ? 0 : x - y);
							}
							else {
								n(x);
							}
						}
					});
					var n = function(z){
						if (p.attr("sel") == 1) {
							var y = parseInt(d) - z;
							if (y > 0) {
								f(z);
							}
							else {
								f(parseInt(d));
							}
						}
					};
				};
				
				if (parseInt(d) > 0) {
					p.parent().click(function(){
					
						k(0);
						if (p.attr("sel") == 1) {
							f(0);
							l(x);
						}
						else {
							var y = parseInt(d);
							if (y > 0) {
								f(y >= x ? x : y);
								l(y >= x ? 0 : x - y);
							}
							else {
								l(x);
							}
						}
					});
					var l = function(z){
						if (c.attr("sel") == 1) {
							var y = ffdk - z;
							if (y > 0) {
								q(z);
							}
							else {
								q(ffdk);
								k(-y);
							}
						}
						else {
							k(z);
						}
					};
				};
				
				if (c.length > 0) {
					c.parent().click();
					p.parent().unbind("click");
					c.parent().unbind("click");
				}
				else 
					if (p.length > 0) {
						p.parent().click();
						p.parent().unbind("click");
						c.parent().unbind("click");
						
					}
				
				var o = false;
				var v = 1;
				var s = $("#btnPay");
				var u = function(){
					if (us.address) {
						api.alert({
							title: '提示',
							msg: '请添加收货地址'
						}, function(index, err){
						});
						return false;
					}
					var submitcode = Path.submitcode;
					if (!this.cc) {
						this.cc = 1;
					}
					else {
					
						api.alert({
							title: '提示',
							msg: '不可以重复提交订单'
						}, function(index, err){
						});
						return false;
					}
					
					if (checkpay == 'nosel') {
						api.alert({
							title: '提示',
							msg: '请选择一种支付方式！'
						}, function(index, err){
						});
						if (this.cc) {
							this.cc = false;
						}
						return;
					}
					if (!a) {
						return;
					}
					if (w + g >= x) {
						a = false;
						s.unbind("click").addClass("dis");
						if (shopnum != -1) {
							if (shopnum == 0) {
								$.PageDialog.fail('购物车中没有商品哦');
								localData.remove('cart');
								localData.remove('cart_num');
								return;
							}
							else {
								//checkpay 支付类型 money 余额支付
								//banktype 选择支付平台 微信支付，支付宝支付
								//t 积分
								//x 商品金额
								$('#btnPay').addClass('btnPay');
								$('.actionPay').addClass('private');
								api.showProgress({
									title: '正在支付',
									text: ''
								});
								PostData(config.url + '/app.php?act=zpaysubmit&uid=' + userinfo.uid, {
									submit: true,
									bag: 'b',
									checkpay: checkpay,
									banktype: banktype,
									money: x,
									score: t,
									cart: localData.get('z_cart'),
								}, function(data){
									api.hideProgress();
									localData.remove('z_cart');
									localData.remove('z_cart_num');
									if (data['status']) {
										appClose('z_cart', api);
										$('#btnPay').hide();
										$('.actionPay').hide();
										api.alert({
											title: '提示',
											msg: data['msg'],
										}, function(index, err){
											randomSwitchBtn('z_paysuccess', api);
											appClose('z_payment', api);
										});
										
									}
									else {
										$('#btnPay').removeClass('btnPay');
										$('.actionPay').removeClass('private');
										$('.actionPay').hide();
										api.alert({
											title: '提示',
											msg: data['msg']
										}, function(index, err){
											appClose('z_payment', api);
										});
									}
								});
							}
						}
						s.bind("click", u).removeClass("dis");
						a = true;
					}
					else {
						if (e > 0) {
							if (v == 1 || v == 2 || v == 3) {
								//location.href = Gobal.Webpath+"/mobile/cart/paysubmit/"+checkpay+"/"+banktype+"/"+x+"/"+t
							}
						}
					}
				};
				s.bind("click", u);
				a = true;
			}
			
		};
		b();
	});
};